//
//  BindPhoneNumViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/2.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "BindPhoneNumViewController.h"
#import "HeaderFileForEasyToTesco.h"
#import "AFNetworking.h"
#import "RKAlertView.h"

#import "ReadLoginData.h"


@interface BindPhoneNumViewController ()<UITextFieldDelegate>{
    NSString *temp;
    
    NSString *passwordStr;
}


////用户名输入框
//@property (nonatomic, strong)UITextField *useNameText;
////密码输入框
//@property (nonatomic, strong)UITextField *passwordText;
////绑定的手机号码输入框
//@property (nonatomic, strong)UITextField *phoneText;


//用于传递收到的手机短信验证码
@property (nonatomic, copy)NSString *phonenessage;

@end

@implementation BindPhoneNumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self addphoneNumtopview];
    
    
    [self addphoneNumUI];
    
    
}


- (void)addphoneNumtopview {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-20)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"手机号码绑定";

}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)addphoneNumUI{
    NSDictionary *dic = [ReadLoginData readLoginData];
    if (dic.allKeys.count == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请登录后再次操作" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }else {
        self.usernameText.text = [dic[@"data"] objectForKey:@"username"];
    }
    
}

//获取手机验证码的button的点击事件
- (IBAction)GetPhoneMessageClick:(id)sender {
    
    if (self.usernameText.text.length == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未登录,请登录后再次操作" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    } else if ((self.bindPhoneNum.text.length<11)||(![self isMobileNumber:self.bindPhoneNum.text])) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码输入有误,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }else {
    
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.MessageBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.MessageBtn.backgroundColor = [UIColor orangeColor];
                self.MessageBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.MessageBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                self.MessageBtn.backgroundColor = [UIColor grayColor];
                self.MessageBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
    
    [self addPhoneMessage];
    }
}


//确定绑定手机号操作事件
- (IBAction)BindDoneBtnClick:(id)sender {
    if (self.usernameText.text.length != 0  && self.bindPhoneNum.text.length != 0 && self.messageText.text.length != 0) {
        BOOL judge = [self isMobileNumber:self.bindPhoneNum.text];
        if (judge == YES) {
            
                            //弹出密码输入框
                [RKAlertView showAlertPlainTextWithTitle:@"提示框" message:nil cancelTitle:@"取消" confirmTitle:@"确认" alertViewStyle:UIAlertViewStylePlainTextInput confrimBlock:^(UIAlertView *alertView) {
                    NSLog(@"确认了输入：%@",[alertView textFieldAtIndex:0].text);
                    passwordStr = [alertView textFieldAtIndex:0].text;
                     [self addphonenumdatasources];
                    
                } cancelBlock:^{
//                    NSLog(@"取消了");
                }];
            
        } else {
            UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式有误, 请重新输入..." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
        }
        
    } else {
        UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"请完善您的绑定信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    }
    

}

//获取短信验证码数据
- (void)addPhoneMessage {
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = self.usernameText.text;
    NSString *type = @"1";
    NSString *phone = self.bindPhoneNum.text;

    NSLog(@"验证码%@====%@", username, phone);
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username], @"type":[NSString stringWithFormat:@"%@", type], @"phone":[NSString stringWithFormat:@"%@", phone]};
    
    [mgr POST:@"http://www.ylgw8.com/AppPub/Getcode" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
       NSDictionary *dict = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"%@, %@", dict, dict[@"message"]);
        
//        [self addphonenumdatasources];
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"%@", dict[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

//对手机号码进行绑定数据操作
- (void)addphonenumdatasources{
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *username = self.bindPhoneNum.text;
    NSString *password = self.PasswordText.text;
    NSString *verify = self.messageText.text;

    NSLog(@"%@++++%@++++%@", username, password, verify);
    
    NSDictionary *param = @{@"username":[NSString stringWithFormat:@"%@", username], @"password":[NSString stringWithFormat:@"%@", password], @"verify":[NSString stringWithFormat:@"%@", verify]};
    
    [mgr POST:@"http://www.ylgw8.com/AppUser/Setphone" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSDictionary *dic = [self toArrayOrNSDictionary:responseObject];
        NSLog(@"绑定手机号:%@===-----%@", dic, string);
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@", dic[@"message"]] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
        
        
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
//         NSLog(@"数据请求错误原因:%@", error);
//         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}

// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}



//触摸空白处回收键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    
    
//    [self.usernameText resignFirstResponder];
    [self.PasswordText resignFirstResponder];
    [self.bindPhoneNum resignFirstResponder];
    [self.messageText resignFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.bindPhoneNum) {
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength >= 12) {
            return NO;
        }
        
        if (textField.text.length == 11) {
            if (![self isMobileNumber:textField.text]) {
                UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式有误, 请重新输入..." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alview show];
            }
        }

        
        
    }
    return YES;
}



//实时监控键盘的状态
- (void)textFieldDidChange:(UITextField *)textField{
    if (textField == self.bindPhoneNum) {
        if (textField.text.length >=12) {
            textField.text = [textField.text substringToIndex:12];
        }
        
        if (textField.text.length == 11) {
            if (![self isMobileNumber:textField.text]) {
                UIAlertView *alview =[[ UIAlertView alloc] initWithTitle:@"提示" message:@"手机号码格式有误, 请重新输入..." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                self.bindPhoneNum.text = nil;
                [alview show];
            }
        }

        
    }
}


//判断手机号码
- (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188, 183
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186 145
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189  181
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
